<template>
  <div class="main section clearfix">
    <el-form :inline="true" style="text-align: left" :model="query">
      <el-row>
        <el-col :span="4">
          <el-form-item label="关键词:">
            <el-input
              placeholder="审批流名称"
              v-model="query.approveFlowName"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item class="btn">
            <el-button type="danger" @click="clearAudit" v-no-more-click
              >清空</el-button
            >
            <el-button type="primary" @click="searchAudit" v-no-more-click
              >搜索</el-button
            >
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item class="btn">
            <el-button
              type="primary"
              @click="approveAdd"
              v-if="approveFlowSaveBtn"
              v-no-more-click
              >+添加</el-button
            >
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-table :data="tableData" style="width: 100%" border stripe>
      <el-table-column
        prop="approveFlowName"
        label="审批流名称"
        align="center"
        :show-overflow-tooltip="true"
      >
      </el-table-column>
      <el-table-column prop="flowInit" label="初始状态" align="center">
      </el-table-column>
      <el-table-column prop="flowEnd" label="结束状态" align="center">
      </el-table-column>
      <el-table-column prop="flowSum" label="总批级数" align="center">
      </el-table-column>
      <el-table-column prop="createDate" label="创建日期" align="center">
      </el-table-column>
      <el-table-column
        prop="approveExplain"
        label="说明"
        align="center"
        :show-overflow-tooltip="true"
      >
      </el-table-column>
      <el-table-column prop="updateTime" label="更新时间" align="center">
      </el-table-column>
      <el-table-column
        fixed="right"
        label="操作"
        width="150"
        align="center"
        v-if="approveFlowdUpdateBtn || approveFlowdDleteBtn"
      >
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            @click="updateApprove(scope.row)"
            v-if="approveFlowdUpdateBtn"
            v-no-more-click
            >编辑</el-button
          >
          <el-popconfirm
            title="确定删除此数据吗？"
            @onConfirm="deleteData(scope.$index, scope.row)"
            v-if="approveFlowdDleteBtn"
          >
            <el-button
              slot="reference"
              type="text"
              size="small"
              v-if="approveFlowdDleteBtn"
              v-no-more-click
              >删除</el-button
            >
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!--    分页-->
    <div class="pagination">
      <span class="title">小计：共{{ this.query.total }}条数据</span>
      <el-pagination
        background
        layout="total,prev, pager, next"
        :total="query.total"
        :page-size="query.pagesize"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      >
      </el-pagination>
    </div>

    <!--    新增编辑对话框-->
    <el-dialog
      :title="title"
      :close-on-click-modal="false"
      :show-close="false"
      :visible.sync="dialogVisible"
      width="50%"
      @close="closeDialog"
      v-if="dialogVisible"
    >
      <div class="span">
        <span style="color: red">*</span
        ><span>审批流的初始状态与结束状态必须与数据库中的状态保持一致</span>
      </div>
      <el-form
        :model="formInline"
        ref="formInline"
        :rules="rules"
        label-width="100px"
      >
        <el-row>
          <el-col :span="5.5" style="height: 48px">
            <el-form-item label="审批流名称:" prop="approveFlowName">
              <el-input
                v-model="formInline.approveFlowName"
                placeholder="请输入审批流名称"
                style="width: 150px"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5.5" style="height: 48px">
            <el-form-item label="开始状态:" prop="flowInit">
              <el-input
                v-model="formInline.flowInit"
                placeholder="请输入开始状态"
                style="width: 150px"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8" style="height: 48px">
            <el-form-item label="结束状态:" prop="flowEnd">
              <el-input
                v-model="formInline.flowEnd"
                placeholder="请输入结束状态"
                style="width: 150px"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="说明:" prop="approveExplain">
              <el-input
                type="textarea"
                :rows="1"
                v-model="formInline.approveExplain"
                placeholder="请输入说明"
                style="width: 350px"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="approcalForm" ref="scrollBox">
        <vuedraggable
          :list="approveModels"
          :disabled="!enabled"
          class="list-group"
          ghost-class="ghost"
          @start="dragging = true"
          @end="endDraggin"
        >
          <ApprocalDialog
            v-for="(item, index) in approveModels"
            :key="index"
            :index="index"
            :item="item"
            :approveModels="approveModels"
            :deptData="deptData"
            :roleData="roleData"
            :newfun="newfun"
            :v-if="approveModels.length >= 1"
            @delDialog="deleteIndex"
            @func="getMsgFormSon"
            ref="formList"
          >
          </ApprocalDialog>
        </vuedraggable>
      </div>
      <div class="btn">
        <el-button @click="addForm" v-no-more-click>添加一级</el-button>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancleDia" v-no-more-click>取 消</el-button>
        <el-button type="primary" @click="submit" v-no-more-click
          >提 交</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import ApprocalDialog from "../../components/system/ApprocalDialog";
import vuedraggable from "vuedraggable";
import {
  // orginlistTree,
  // getRoleList,
  getApproveOne,
  approveFlowAdd,
  approveFlowUpdate,
  delApprove,
  departAdd,
  // getApproveList
} from "../../../src/assets/js/api";
import { checkPermiss } from "../../assets/js/utlis";
export default {
  name: "Approval",
  components: { ApprocalDialog, vuedraggable },
  data() {
    return {
      enabled: true,
      dragging: false,
      dialogVisible: false,
      formInline: {},
      newfun: "",
      approveModels: [
        {
          // approveModelName: "",
          // departmentType: "",
          // firmId: "",
          // departmentId: "",
          // appointType: "",
          // employeeId: null,
          // roleId: null
          // moduleExplain: "",
          // standardOpinion: "",
          // modelCode: ""
        },
      ],
      // 查询
      query: {
        pagesize: 10,
        pageNo: 1,
        total: 10,
        pages: 0,
        approveFlowName: "",
      },
      tableData: [],
      deptData: [
        { id: 0, label: "不限部门" },
        { id: 1, label: "所在部门" },
        { id: 2, label: "公司及部门树" },
      ],
      roleData: [
        { id: 1, roleName: "按角色" },
        { id: 2, roleName: "指定人" },
      ],
      title: "",
      msgFormSon: "",
      rules: {
        approveFlowName: [
          // required: 非空规则
          // message: 提示信息
          // trigger: 触发的方式 change
          { required: true, message: "请输入审批流名称", trigger: "blur" },
          {
            min: 1,
            max: 12,
            message: "长度在 3 到 12 个字符",
            trigger: "change",
          },
        ],
        flowInit: [
          { required: true, message: "请输入开始状态", trigger: "blur" },
        ],
        flowEnd: [
          { required: true, message: "请输入结束状态", trigger: "blur" },
        ],
        approveExplain: [
          { required: true, message: "请输入说明", trigger: "blur" },
        ],
        approveModelName: [
          { required: true, message: "请输入名称", trigger: "blur" },
        ],
        departmentType: [
          { required: true, message: "请输入说明", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.golbalPermissions = localStorage.getItem("permissions").split(",");
    this.getlist();
  },
  computed: {
    //  添加
    approveFlowSaveBtn: function () {
      return checkPermiss("sys:approveFlow:save", this.golbalPermissions);
    },
    // 删除
    approveFlowdDleteBtn: function () {
      return checkPermiss("sys:approveFlow:delete", this.golbalPermissions);
    },
    // 编辑
    approveFlowdUpdateBtn: function () {
      return checkPermiss("sys:approveFlow:update", this.golbalPermissions);
    },
  },
  methods: {
    //拖动结束
    endDraggin() {
      this.dragging = false;
    },
    // 获取表格数据
    getlist() {
      const token = localStorage.getItem("token");
      this.axios
        .get("/sys/approveFlow/page", {
          //参数列表
          params: this.query,
          //请求头配置
          headers: { token: token },
        })
        .then((res) => {
          this.tableData = res.data.data.records;
          this.query.pagesize = res.data.data.size;
          this.query.pageNo = res.data.data.current;
          this.query.total = res.data.data.total;
          this.query.pages = res.data.data.pages;
        });
    },
    //点击编辑按钮事件
    async updateApprove(obj = {}) {
      this.newfun = 1;
      const { data } = await getApproveOne(obj.id);
      obj = data.approveModels;
      this.formInline = data;
      this.title = "编辑";
      obj.map(async (item) => {
        if (item.firmId !== null) {
          const { data } = await departAdd(item.firmId);
          item["deptList"] = [...data];
        }
      });
      this.approveModels = obj;
      this.$nextTick(() => {
        this.dialogVisible = true;
      });
    },
    getMsgFormSon(data) {
      this.msgFormSon = data;
    },
    // 搜索按钮操作
    searchAudit() {
      this.query.pageNo = 1;
      this.getlist();
    },
    // 清空按钮操作
    clearAudit() {
      this.query.approveFlowName = "";
      this.query.pageNo = 1;
      this.getlist();
    },
    // 取消按钮
    cancleDia() {
      this.dialogVisible = false;
      this.approveModels = [];
    },
    // 删除
    deleteData(index, obj) {
      delApprove(obj.id).then((res) => {
        if (res.code === 200) {
          this.$message({
            message: res.message,
            type: "success",
          });
          this.getlist(this.query);
        } else {
          this.$message({
            message: res.message,
            type: "error",
          });
          this.getlist(this.query);
        }
      });
    },
    // 添加一级按钮
    addForm() {
      this.approveModels.push({
        employeeId: null,
        roleId: null,
      });
      let div = this.$refs.scrollBox;
      setTimeout(() => {
        div.scrollTop = div.scrollHeight;
      }, 0);
    },
    // 删除添加的表单
    deleteIndex(item) {
      let arr = this.approveModels;
      const removeItem = (items, i) =>
        items.slice(0, i).concat(items.slice(i + 1, items.length));
      this.approveModels = removeItem(arr, item);
    },
    //关闭弹框的事件
    closeDialog() {
      this.$refs.formInline.resetFields();
    },
    // 添加按钮操作
    approveAdd() {
      this.dialogVisible = true;
      this.approveModels = [];
      this.formInline = {};
      this.newfun = 0;
      // if (this.formInline.length != 0) {
      //   this.$refs.formInline.resetFields();
      // }
      this.title = "新增";
    },
    // 新增修改提交
    submit() {
      // this.getMsgFormSon();
      // this.formInline.approveModels.employeeId = this.msgFormSon;
      // this.approveModels.map(item => {
      //   item.employeeId = this.msgFormSon;
      //   return item;
      // });
      this.formInline.approveModels = this.approveModels;
      if (this.formInline.approveModels.length > 0) {
        let fun = this.formInline.approveModels.map((item) => {
          if (!item.approveModelName) {
            this.$message({
              message: "请输入名称",
              type: "error",
            });
            return false;
          }

          if (!item.departmentType && item.departmentType != 0) {
            this.$message({
              message: "请选择审批人",
              type: "error",
            });
            return false;
          }
          if (item.departmentType == 2) {
            if (!item.firmId) {
              this.$message({
                message: "请选择公司",
                type: "error",
              });
              return false;
            }
            if (!item.departmentId) {
              this.$message({
                message: "请选择部门",
                type: "error",
              });
              return false;
            }
          }
          if (!item.appointType) {
            this.$message({
              message: "请选择按角色或指定人",
              type: "error",
            });
            return false;
          }
          if (item.appointType == 1) {
            if (!item.roleId) {
              this.$message({
                message: "请选择角色",
                type: "error",
              });
              return false;
            }
          }
          if (item.appointType == 2) {
            if (!item.employeeId) {
              this.$message({
                message: "请选择指定人",
                type: "error",
              });
              return false;
            }
          }
        });
        for (var i = 0; i < fun.length; i++) {
          if (fun[i] == false) {
            return false;
          }
        }
        fun.map;
      }
      this.$refs.formInline.validate((valid) => {
        if (!valid) {
          return false;
        }
        this.formInline.approveModels.map((item) => {
          if (item.chinaId !== null) {
            item.employeeId = item.chinaId;
          }
          return item;
        });
        if (this.formInline.id) {
          approveFlowUpdate(this.formInline).then((res) => {
            if (res.code === 200) {
              this.dialogVisible = false;
              this.$message({
                message: res.message,
                type: "success",
              });
              this.getlist(this.query);
              this.approveModels = [];
            } else {
              this.dialogVisible = false;
              this.$message({
                message: res.message,
                type: "error",
              });
              this.getlist(this.query);
              this.approveModels = [];
            }
          });
        } else {
          approveFlowAdd(this.formInline).then((res) => {
            if (res.code === 200) {
              this.dialogVisible = false;
              this.$message({
                message: res.message,
                type: "success",
              });
              this.getlist(this.query);
              this.approveModels = [];
            } else {
              this.dialogVisible = false;
              this.$message({
                message: res.message,
                type: "error",
              });
              this.getlist(this.query);
              this.approveModels = [];
            }
          });
        }
      });
    },
    //分页
    handleCurrentChange(cpage) {
      this.query.pageNo = cpage;
      this.getlist(cpage);
    },
    handleSizeChange(psize) {
      this.query.pageNo = psize;
      this.getlist(psize);
    },
  },
  //监听删除数据如果是这一页的最后一条数据，返回上一页
  watch: {
    "query.total": {
      handler() {
        if (
          this.query.total == (this.query.pageNo - 1) * this.query.pagesize &&
          this.query.total != 0
        ) {
          this.query.pageNo -= 1;
          this.getlist(); //获取列表数据
        }
      },
      deep: true,
      immediate: true,
    },
  },
};
</script>
<style scoped type="less">
.el-pagination
{
    text-align: right;
}
.span
{
    height: 40px;  text-align: left;
}
.btn
{
    padding-left: 40px;  text-align: left;
}
.el-dialog__footer
{
    text-align: center;
}
.ghost
{
    opacity: .5;  background: #c8ebfb;
}
.approcalForm
{
    overflow-x: hidden;  max-height: 410px;
}
::v-deep .el-table td
{
    padding: 10px 0;
}
::v-deep .el-table th
{
    padding: 10px 0;
}
::v-deep .el-form-item__content
{
    text-align: left;
}
::v-deep .el-input__inner
{
    height: 30px;
}
::v-deep .el-dialog__body
{
    padding: 0 20px 0 20px;
}
::v-deep .el-form--inline .el-form-item__content
{
    line-height: 42px;  width: 210px;
}
::v-deep .el-input__inner
{
    height: 32px;
}
::v-deep .el-input__icon
{
    line-height: 32px;
}
::v-deep .btn .el-button
{
    line-height: 0;  height: 32px;
}
::v-deep .el-table th > .cell
{
    font-size: 14px;  font-weight: bold;  color: #333;
}
::v-deep .el-table--striped .el-table__body tr.el-table__row--striped td
{
    background: rgba(59, 157, 248, .1);
}
.main
{
    position: relative;
}
::v-deep .el-pagination
{
    position: absolute;  right: 0;  margin-top: 20px;
}
::v-deep .el-pagination__total
{
    visibility: hidden;
}
.title
{
    font-family: Microsoft YaHei;  font-size: 12px;  font-weight: 400;  line-height: 21px;  position: absolute;  left: 0;  margin-top: 15px;  color: rgba(51, 51, 51, 1);
}



</style>
